'use strict';
const db = uniCloud.database();
const videoDataCollection = db.collection('video_data');
const userCollection = db.collection('users');

// 常量定义
const LOG_PREFIX = '[VideoManage]';
const DOC_TYPE = {
  VIDEO: 'video',
  HISTORY: 'watch_history'
};
const ERROR_CODE = {
  PARAM_MISSING: -1,
  PERMISSION_DENIED: -2,
  NOT_FOUND: -3,
  VALIDATION_FAILED: -4,
  INTERNAL_ERROR: -500
};
const POINTS_CONFIG = {
  MIN_WATCH_RATIO: 0.5, // 获得积分的最小观看比例
  MAX_POINTS_PER_VIDEO: 10 // 单个视频可获得的最高积分
};

/**
 * 主入口函数
 */
exports.main = async (event, context) => {
  const { action, user_id, video_id, ...params } = event;
  
  console.log(`${LOG_PREFIX} 调用开始`, { action, user_id, video_id });

  try {
    // 基础验证
    if (!action) {
      return errorResponse('缺少action参数', ERROR_CODE.PARAM_MISSING);
    }

    // 权限验证
    if (requiresAdminPermission(action)) {
      const authResult = await verifyAdminPermission(user_id);
      if (!authResult.success) {
        return errorResponse(authResult.message, ERROR_CODE.PERMISSION_DENIED);
      }
    }

    // 路由处理
    switch (action) {
      case 'get':
        return await handleGetVideos({ user_id, ...params });
      case 'add':
        return await handleAddVideo(params);
      case 'batchAdd':
        return await handleBatchAddVideos(params);
      case 'update':
        return await handleUpdateVideo({ video_id, ...params });
      case 'delete':
        return await handleDeleteVideo(video_id);
      case 'watch':
        return await handleWatchVideo({ user_id, video_id, ...params });
      case 'saveProgress':
        return await handleSaveProgress({ user_id, video_id, ...params });
      case 'getHistory':
        return await handleGetHistory({ user_id, ...params });
      default:
        return errorResponse('无效的操作', ERROR_CODE.PARAM_MISSING);
    }
  } catch (e) {
    console.error(`${LOG_PREFIX} 操作失败`, { 
      action, 
      error: e.message,
      stack: e.stack 
    });
    return errorResponse(`操作失败: ${e.message}`, ERROR_CODE.INTERNAL_ERROR);
  }
};

// ============== 工具函数 ==============

/**
 * 错误响应
 */
function errorResponse(msg, code = ERROR_CODE.PARAM_MISSING, data = null) {
  return { code, msg, data };
}

/**
 * 成功响应
 */
function successResponse(data = null, msg = '操作成功') {
  return { code: 0, data, msg };
}

/**
 * 验证管理员权限
 */
async function verifyAdminPermission(user_id) {
  if (!user_id) {
    console.log(`${LOG_PREFIX} 权限验证失败: 用户ID为空`);
    return { success: false, message: '用户ID不能为空' };
  }
  
  const userRes = await userCollection.doc(user_id).get();
  console.log(`${LOG_PREFIX} 用户查询结果:`, userRes.data);
  if (userRes.data.length === 0 || !['admin', 'teacher'].includes(userRes.data[0].role)) {
      console.log(`${LOG_PREFIX} 权限验证失败: 非管理员或教师`, { user_id });
      return { success: false, message: '无管理员或教师权限' };
    }
  
  return { success: true };
}

/**
 * 检查操作是否需要管理员权限
 */
function requiresAdminPermission(action) {
  return ['add', 'batchAdd', 'update', 'delete'].includes(action);
}

/**
 * 验证视频数据
 */
function validateVideoData(video) {
  const { title, url, duration, category, category_label } = video;
  if (!title || !url || !duration || !category || !category_label) {
    throw new Error('视频信息不完整');
  }
  
  if (typeof duration !== 'number' || duration <= 0) {
    throw new Error('视频时长必须为正数');
  }
}

// ============== 核心处理函数 ==============

/**
 * 获取视频列表
 */
async function handleGetVideos({ user_id, category, keyword, page = 1, pageSize = 10 }) {
  const query = { type: DOC_TYPE.VIDEO };
  
  if (category) query.category = category;
  if (keyword) {
    query.title = db.RegExp({ 
      regexp: keyword, 
      options: 'i' 
    });
  }
  
  // 分页查询
  const { data: videos, requestId } = await videoDataCollection
    .where(query)
    .orderBy('created_at', 'desc')
    .skip((page - 1) * pageSize)
    .limit(pageSize)
    .get();
  
  console.log(`${LOG_PREFIX} 获取视频列表`, { 
    requestId, 
    count: videos.length 
  });

  // 获取观看进度
  let progressMap = {};
  if (user_id) {
    const videoIds = videos.map(video => video._id);
    const { data: histories } = await videoDataCollection
      .where({ 
        type: DOC_TYPE.HISTORY, 
        user_id, 
        video_id: db.command.in(videoIds) 
      })
      .get();
      
    histories.forEach(history => {
      progressMap[history.video_id] = {
        progress: history.progress || 0,
        last_watch: history.updated_at
      };
    });
  }
  
  // 格式化响应数据
  const result = videos.map(video => ({
    id: video._id,
    title: video.title,
    url: video.url,
    duration: video.duration,
    category: video.category,
    category_label: video.category_label,
    created_at: video.created_at,
    updated_at: video.updated_at,
    progress: progressMap[video._id]?.progress || 0,
    last_watch: progressMap[video._id]?.last_watch || null
  }));
  
  return successResponse(result, '获取视频列表成功');
}

/**
 * 添加单个视频
 */
async function handleAddVideo(videoData) {
  try {
    validateVideoData(videoData);
  } catch (e) {
    return errorResponse(e.message, ERROR_CODE.VALIDATION_FAILED);
  }
  
  const { title, url, duration, category, category_label } = videoData;
  const newId = `video_${Date.now()}`;
  const now = new Date();
  
  await videoDataCollection.add({
    _id: newId,
    type: DOC_TYPE.VIDEO,
    title,
    url,
    duration,
    category,
    category_label,
    created_at: now,
    updated_at: now
  });
  
  console.log(`${LOG_PREFIX} 视频添加成功`, { id: newId, title });
  
  return successResponse({ id: newId }, '添加视频成功');
}

/**
 * 批量添加视频
 */
async function handleBatchAddVideos({ videos }) {
  if (!Array.isArray(videos) || videos.length === 0) {
    return errorResponse('视频列表不能为空', ERROR_CODE.VALIDATION_FAILED);
  }
  
  // 验证所有视频数据
  try {
    videos.forEach(validateVideoData);
  } catch (e) {
    return errorResponse(e.message, ERROR_CODE.VALIDATION_FAILED);
  }
  
  const now = new Date();
  const batchVideos = videos.map(video => ({
    _id: `video_${now.getTime()}_${Math.random().toString(36).slice(2, 8)}`,
    type: DOC_TYPE.VIDEO,
    title: video.title,
    url: video.url,
    duration: video.duration,
    category: video.category,
    category_label: video.category_label,
    created_at: now,
    updated_at: now
  }));
  
  await videoDataCollection.add(batchVideos);
  
  console.log(`${LOG_PREFIX} 批量添加视频成功`, { count: batchVideos.length });
  
  return successResponse(
    { count: batchVideos.length }, 
    `成功添加 ${batchVideos.length} 个视频`
  );
}

/**
 * 更新视频
 */
async function handleUpdateVideo({ video_id, ...updateData }) {
  if (!video_id) {
    return errorResponse('视频ID不能为空', ERROR_CODE.PARAM_MISSING);
  }
  
  // 过滤有效更新字段
  const validFields = ['title', 'url', 'duration', 'category', 'category_label'];
  const filteredData = {};
  
  validFields.forEach(field => {
    if (updateData[field] !== undefined) {
      filteredData[field] = updateData[field];
    }
  });
  
  if (Object.keys(filteredData).length === 0) {
    return errorResponse('没有可更新的数据', ERROR_CODE.VALIDATION_FAILED);
  }
  
  // 添加更新时间
  filteredData.updated_at = new Date();
  
  const updateRes = await videoDataCollection.doc(video_id).update(filteredData);
  
  console.log(`${LOG_PREFIX} 视频更新成功`, { video_id, updated: filteredData });
  
  return successResponse(updateRes, '更新视频成功');
}

/**
 * 删除视频
 */
async function handleDeleteVideo(video_id) {
  if (!video_id) {
    return errorResponse('视频ID不能为空', ERROR_CODE.PARAM_MISSING);
  }
  
  // 使用事务确保数据一致性
  await db.startTransaction();
  try {
    // 检查视频是否存在
    const videoRes = await videoDataCollection.doc(video_id).get();
    if (videoRes.data.length === 0) {
      await db.rollbackTransaction();
      return errorResponse('视频不存在', ERROR_CODE.NOT_FOUND);
    }
    
    // 删除视频
    await videoDataCollection.doc(video_id).remove();
    
    // 删除相关观看记录
    await videoDataCollection
      .where({ type: DOC_TYPE.HISTORY, video_id })
      .remove();
    
    await db.commitTransaction();
    
    console.log(`${LOG_PREFIX} 视频删除成功`, { video_id });
    
    return successResponse(null, '删除视频成功');
  } catch (e) {
    await db.rollbackTransaction();
    throw e;
  }
}

/**
 * 处理观看视频
 */
async function handleWatchVideo({ user_id, video_id, watch_time, duration }) {
  const requiredParams = { user_id, video_id, watch_time, duration };
  for (const [key, value] of Object.entries(requiredParams)) {
    if (value === undefined || value === null) {
      return errorResponse(`缺少必要参数: ${key}`, ERROR_CODE.PARAM_MISSING);
    }
  }
  
  // 验证视频是否存在
  const videoRes = await videoDataCollection.doc(video_id).get();
  if (videoRes.data.length === 0) {
    return errorResponse('视频不存在', ERROR_CODE.NOT_FOUND);
  }
  
  // 检查是否已获得积分
  const historyRes = await videoDataCollection
    .where({ 
      type: DOC_TYPE.HISTORY, 
      user_id, 
      video_id, 
      watch_time: db.command.gte(duration * POINTS_CONFIG.MIN_WATCH_RATIO)
    })
    .get();
  
  if (historyRes.data.length > 0) {
    return successResponse({ points: 0 }, '已获得该视频积分');
  }
  
  // 计算应得积分
  let pointsEarned = 0;
  const watchRatio = watch_time / duration;
  
  if (watchRatio >= POINTS_CONFIG.MIN_WATCH_RATIO) {
    pointsEarned = Math.min(
      Math.floor(watch_time / 60), 
      POINTS_CONFIG.MAX_POINTS_PER_VIDEO
    );
  }
  
  // 使用事务确保数据一致性
  await db.startTransaction();
  try {
    // 更新或创建观看记录
    const existingHistory = await videoDataCollection
      .where({ type: DOC_TYPE.HISTORY, user_id, video_id })
      .get();
    
    const now = new Date();
    if (existingHistory.data.length > 0) {
      await videoDataCollection
        .where({ type: DOC_TYPE.HISTORY, user_id, video_id })
        .update({ 
          watch_time, 
          duration, 
          progress: watch_time,
          updated_at: now 
        });
    } else {
      await videoDataCollection.add({
        _id: `history_${now.getTime()}`,
        type: DOC_TYPE.HISTORY,
        user_id,
        video_id,
        watch_time,
        duration,
        progress: watch_time,
        created_at: now,
        updated_at: now
      });
    }
    
    // 更新用户积分
    if (pointsEarned > 0) {
      const userRes = await userCollection.doc(user_id).get();
      if (userRes.data.length === 0) {
        await db.rollbackTransaction();
        return errorResponse('用户不存在', ERROR_CODE.NOT_FOUND);
      }
      
      const currentPoints = userRes.data[0].points || 0;
      await userCollection
        .doc(user_id)
        .update({ 
          points: currentPoints + pointsEarned, 
          updated_at: now 
        });
    }
    
    await db.commitTransaction();
    
    console.log(`${LOG_PREFIX} 观看记录更新成功`, { 
      user_id, 
      video_id, 
      pointsEarned 
    });
    
    return successResponse({ points: pointsEarned }, '记录观看成功');
  } catch (e) {
    await db.rollbackTransaction();
    throw e;
  }
}

/**
 * 保存播放进度
 */
async function handleSaveProgress({ user_id, video_id, progress }) {
  if (!user_id || !video_id || progress == null) {
    return errorResponse('参数不完整', ERROR_CODE.PARAM_MISSING);
  }
  
  // 验证视频是否存在
  const videoRes = await videoDataCollection.doc(video_id).get();
  if (videoRes.data.length === 0) {
    return errorResponse('视频不存在', ERROR_CODE.NOT_FOUND);
  }
  
  const now = new Date();
  
  // 检查是否已有观看记录
  const existingHistory = await videoDataCollection
    .where({ type: DOC_TYPE.HISTORY, user_id, video_id })
    .get();
  
  if (existingHistory.data.length > 0) {
    // 更新现有记录
    await videoDataCollection
      .where({ type: DOC_TYPE.HISTORY, user_id, video_id })
      .update({ 
        progress, 
        updated_at: now 
      });
  } else {
    // 创建新记录
    await videoDataCollection.add({
      _id: `history_${now.getTime()}`,
      type: DOC_TYPE.HISTORY,
      user_id,
      video_id,
      progress,
      created_at: now,
      updated_at: now
    });
  }
  
  console.log(`${LOG_PREFIX} 进度保存成功`, { user_id, video_id, progress });
  
  return successResponse(null, '保存进度成功');
}

/**
 * 获取用户观看历史
 */
async function handleGetHistory({ user_id, page = 1, pageSize = 10 }) {
  if (!user_id) {
    return errorResponse('用户ID不能为空', ERROR_CODE.PARAM_MISSING);
  }
  
  // 获取观看历史
  const { data: histories, requestId } = await videoDataCollection
    .where({ type: DOC_TYPE.HISTORY, user_id })
    .orderBy('updated_at', 'desc')
    .skip((page - 1) * pageSize)
    .limit(pageSize)
    .get();
  
  console.log(`${LOG_PREFIX} 获取观看历史`, { 
    requestId, 
    user_id, 
    count: histories.length 
  });
  
  if (histories.length === 0) {
    return successResponse([], '暂无观看历史');
  }
  
  // 获取相关视频信息
  const videoIds = histories.map(h => h.video_id);
  const { data: videos } = await videoDataCollection
    .where({ 
      _id: db.command.in(videoIds),
      type: DOC_TYPE.VIDEO
    })
    .get();
  
  const videoMap = {};
  videos.forEach(video => {
    videoMap[video._id] = video;
  });
  
  // 合并数据
  const result = histories.map(history => {
    const video = videoMap[history.video_id] || {};
    return {
      history_id: history._id,
      video_id: history.video_id,
      title: video.title || '未知视频',
      duration: video.duration || 0,
      category: video.category,
      category_label: video.category_label,
      progress: history.progress || 0,
      watch_time: history.watch_time || 0,
      last_watch: history.updated_at,
      video_url: video.url
    };
  });
  
  return successResponse(result, '获取观看历史成功');
}